package com.xinuo.sqlprocessing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;

/**
 * 1.修改待导入SQL中的字符集编码及排序规则
 * 2.通过正则表达式指定只保留表结构的表名规则
 */
public class ModifyCharacterFilterTable {

    public static void  fileHandling () throws FileNotFoundException, UnsupportedEncodingException {
        FileReader fileReader = null;
        BufferedReader br = null;
        String line = null;
        File fileWrite = new File("D:\\Libraries\\Desktop\\newFile.sql");
        BufferedWriter bufferOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileWrite, true), "UTF-8"));

        try {
            // 待处理文件
            File pendingFile = new File("D:\\Libraries\\Desktop\\dscm_uat.sql");
            if (!pendingFile.exists()){
                System.out.println(pendingFile.getName() + " isn't existed");
            }
            // 带缓存功能的输入流
            br = new BufferedReader(new FileReader(pendingFile));
            line = br.readLine();
            while (line != null) {
                // 所有表名中满足x_log、x_log_x、x_copy1、x_20210101、x_20210101_1、x_20210101-1此种规则的插入语句都将被忽略
                if (Pattern.matches("^INSERT INTO `.*((_log(_.*)?)|(_copy(\\d*))|(_\\d*)?([_-]\\d*))`.*;$", line)) {
                    line = br.readLine();
                    continue;
                }
                //将待处理文件中的字符集及排序规则修改成指定格式
                String newLineStr = line.replace("utf8mb4", "utf8").replace("utf8_0900_ai_ci", "utf8_general_ci");
                System.out.println(newLineStr);
                bufferOut.write(newLineStr);
                bufferOut.newLine();
                line = br.readLine();
            }
            System.out.println("----------------------SQL文件处理结束-----------------------");
        } catch (Exception e) {
            e.toString();
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (Exception e) {
                    e.toString();
                    br = null;
                }
            if (fileReader != null)
                try {
                    fileReader.close();
                } catch (Exception e) {
                    e.toString();
                }
            try {
                if (bufferOut != null)
                    bufferOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            fileHandling();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
